/*
 * Filename:  SafeResource.java
 * Copyright:  Raisecom Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * Description:  <description>
 * Author:  donghu
 * Edit-time:  2016-5-4
 * Modify content:  <modify content>
 */
package com.gutetec.cms.usmc.resource;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.RedirectionException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gutetec.cms.usmc.bean.LoginInfo;
import com.gutetec.cms.usmc.bean.LoginResult;
import com.gutetec.cms.usmc.util.UsmcUtil;
import com.gutetec.cms.usmc.util.ValidateImageGenerator;
import com.gutetec.cms.usmc.wrapper.SafeService;

/**
 * <Security policy business process>
 * <Security policy business process>
 * @author  donghu
 * @version  [version, 2016-5-4]
 * @see  [class/function]
 * @since  [version]
 */
@Path("/usmc/v1")
@Api(tags = {"umc safe"})
@Produces(MediaType.APPLICATION_JSON)
public class SafeResource
{
    
    private static final String SSOLOGOUT = "SSOLogout";
    
    private static final String DEFAULT_URL = "/iui/framework/login.html";
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SafeResource.class);
    
    @POST
    @Path("/login")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "login ", response = JSONObject.class)
    @Timed
    public JSONObject doLogin(
        @ApiParam(value = "login info", required = true) LoginInfo logininfo,
        @Context HttpServletRequest request, @Context HttpServletResponse servletResponse)
    {
        JSONObject object = new JSONObject();
        String code = logininfo.getVcode();
        
        if (null == code || null == UsmcUtil.generateCodeMap.get(code.toLowerCase()))
        {
            object.put("result", "6");
        }
        else
        {
            UsmcUtil.generateCodeMap.remove(code);
            
            LoginResult result = SafeService.getInstance().doLogin(logininfo);
            
            object.put("result", result.getResult());
            if (result.getCode() == LoginResult.SUCCESS)
            {
                servletResponse.addHeader("ItmsAuth", "true");// set lua auth
                servletResponse.addHeader("username", logininfo.getUsername());// set lua auth
                servletResponse.addHeader("sessioncode", result.getSessioncode());
                object.put("userRole", result.getLoginInfo().getUserRole());
                object.put("userDomain", "");
            }
            else
            {
                servletResponse.addHeader("ItmsAuth", "false");
            }
        }
        
        return object;
        
    }
    
    @GET
    @Path("/loginout")
    @ApiOperation(value = "logout ")
    @Produces(MediaType.APPLICATION_JSON)
    @Timed
    public JSONObject doLogout(
        @ApiParam(value = "loginOut", required = true, allowableValues = SSOLOGOUT) @QueryParam("SSOAction") String SSOAction,
        @Context HttpServletRequest request)
        throws NotFoundException
    {
        if (SSOAction != null & SSOAction.equals(SSOLOGOUT))
        {
        	String sessioncode = SafeService.getInstance().getCookieSessioncode(request);
            SafeService.getInstance().doLogout(sessioncode);
            JSONObject object = new JSONObject();
            object.put("result", "0");
            
            return object;
        }
        throw new NotFoundException("can not found SSOAction :" + SSOAction);
        
    }
    
    @POST
    @Path("/modifypwd")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "login ", response = JSONObject.class)
    @Timed
    public Response modifyPwd(
        @ApiParam(value = "login info", required = true) JSONObject pwdinfo,
        @Context HttpServletRequest request, @Context HttpServletResponse servletResponse)
    {
        
        JSONObject object = SafeService.getInstance().modifyPwd(UsmcUtil.LOGIN_MODIFY_PWD, pwdinfo);
        
        return Response.ok(object).build();
        
    }
    
    @POST
    @Path("/forcespwd")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "login ", response = JSONObject.class)
    @Timed
    public Response forcesPwd(
        @ApiParam(value = "login info", required = true) JSONObject pwdinfo,
        @Context HttpServletRequest request, @Context HttpServletResponse servletResponse)
    {        
        JSONObject object = SafeService.getInstance().modifyPwd(UsmcUtil.LOGIN_FORCES_PWD, pwdinfo);
        if (object.get("result").equals("0"))
        {
            // set user session timer
            //SafeService.getInstance().startUserTimetask(pwdinfo.get("username").toString());
            
            // update user login info
            SafeService.getInstance().setUserLoginInfo(pwdinfo.get("username").toString());
            
            // set lua auth
            servletResponse.addHeader("ItmsAuth", "true");
        }
        return Response.ok(object).build();
        
    }
    
    @POST
    @Path("/passreset")
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "login ", response = JSONObject.class)
    @Timed
    public Response resetPwd(
        @ApiParam(value = "login info", required = true) JSONObject pwdinfo,
        @Context HttpServletRequest request, @Context HttpServletResponse servletResponse)
    {
        JSONObject object = SafeService.getInstance().resetPwd(pwdinfo);
        
        return Response.ok(object).build();
        
    } 
    
    
    @GET
    @Path("/userName")
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(value = "get login username ", response = String.class)
    @Timed
    public String getLoginUserName(@Context HttpServletRequest request, @Context HttpServletResponse response)
    {
         String sessioncode = SafeService.getInstance().getCookieSessioncode(request);
         String user = SafeService.getInstance().getCookieUser(request);
         if(SafeService.getInstance().getSessionTaskMapKey(sessioncode))
         {
        	 SafeService.getInstance().updataUserTimers(sessioncode);
        	 return user;
         }
         return "";
    }
    
    @GET
    @Path("/userheart")
    @ApiOperation(value = "user heart", response = Response.class)
    @Timed
    @Produces(MediaType.APPLICATION_JSON)
    public Response userheart(@ApiParam(value = "sessioncode", required = true) @QueryParam("sessioncode") String sessioncode)
    {
        String status = SafeService.getInstance().getUserSession(sessioncode);
        return Response.ok(status).build();
    }
    
    @GET
    @Path("/generatecode")
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(value = "get verification code")
    @Timed
    public void generateCode(@Context HttpServletRequest request, @Context HttpServletResponse response)
        throws IOException
    {
        request.setCharacterEncoding("UTF-8");
        // get random string
        String randomStr = ValidateImageGenerator.randomStr(4);
        
        // set response
        response.setDateHeader("Expires", 1L);
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
        response.addHeader("Pragma", "no-cache");
        response.addHeader("vcode", randomStr);
        response.setContentType("image/jpeg");
        
        // output page
        ValidateImageGenerator.renderVerificationCode(randomStr, response.getOutputStream(), 70, 30);
    }
}
